package taptap

/*
获取并解析taptap的安卓TOP150榜单
*/

import (
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
)

// GetGameIds 获取TapTap的TOP150数据
func GetGameIds() ([]int, error) {
	var (
		res = [150]int{}  // 结果集
		uri = topStartUri // 初始uri
		idx = 0           // 当前索引
	)
	for uri != "" {
		// 发送请求
		url := genTopUrl(uri)
		response, err := g.Client().Get(url)
		if err != nil {
			return nil, gerror.Newf("请求排行榜失败, err=%v, url=%v", url, err)
		}
		// 校验响应码
		if response.StatusCode != 200 {
			return nil, gerror.Newf("请求排行榜失败, 响应码: %v, 响应体: %v",
				response.StatusCode, response.ReadAllString())
		}
		// 将响应转为json格式
		var taptapResp *taptapTopResp
		jsonString := response.ReadAllString()
		err = gjson.DecodeTo(jsonString, &taptapResp)
		if err != nil {
			return nil, gerror.Newf("排行榜数据格式转换失败, err=%v, json=%v", err, jsonString)
		}
		for _, j := range taptapResp.Data.List {
			res[idx] = j.Id
			idx++
		}
		uri = taptapResp.Data.NextPage
	}
	return res[:idx], nil
}
